package com.oceansoft.mobile.common.aop;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.BusinessThread;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.PvThread;
import com.oceansoft.mobile.common.util.CommonUtilCache;
import com.oceansoft.mobile.weixin.util.DateUtil;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.common.util.Result;

/**
 * Created by jin.xu 2015/3/9 16:38.
 */
@Component
@Aspect
public class ApicallAspect {
    @Autowired
    private HttpServletRequest request;

    private final Logger client = Logger.getLogger("client");

    @Around("execution(* com.oceansoft.mobile.biz.api.controller.*.*(..)) || execution(* com.oceansoft.mobile.biz.front.controller.MicroPoliceController.*(..))")
    public Object beforeMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object object = pjp.proceed();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        String result = "";
        boolean isSucc = false;
//        String args = "";.u
//        Object [] o = pjp.getArgs();
//        for (Object object2 : o) {
//        	args += object2 + "@@@";
//		}

        try {
            if (object instanceof Result) {
                Result cpresult = (Result) BeanUtils.cloneBean(object);
                Object data = ((Result) object).getData();
//                if(!StringUtils.isEmpty(methodName)&&methodName.startsWith("submit"))
//                {
//                	
//                	
//                }
//                else
//                {
//                	
//                }

                if (null != data) {
                    try {
                        if (data.toString().length() > 1000) {
                            data = data.toString().substring(0, 1000);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        data = null;

                    }
                }

                cpresult.setData(data);
                result = JSON.toJSONString(cpresult);
                isSucc = cpresult.isSucc();
            } else {
                result = JSON.toJSONString(object);
                isSucc = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //UserAgent agent = ((UserAgent) request.getAttribute("USER_AGENT_OBJ"));
            //String userId = request.getParameter("USER_ID");
            //String userName = request.getParameter("USER_NAME");
           /* MDC.put("ip", request.getRemoteHost());
            MDC.put("os", agent.getOperatingSystem());
            MDC.put("os_n", agent.getOperatingSystem().getName());
            MDC.put("dt", agent.getOperatingSystem().getDeviceType());
            Browser browser = agent.getBrowser();
            if (null != browser) {
                MDC.put("url", request.getRequestURL());
                MDC.put("bv", null == agent.getBrowserVersion() ? "" : agent.getBrowserVersion());
                MDC.put("bn", agent.getBrowser().getName());
                MDC.put("bg", agent.getBrowser().getGroup());
                MDC.put("bt", agent.getBrowser().getBrowserType());
            } else {
                MDC.put("bv", "");
                MDC.put("bn", "");
                MDC.put("bg", "");
                MDC.put("bt", "");
            }*/
            String url = request.getRequestURL().toString();
            MDC.put("class", pjp.getTarget().getClass().getName());
            /**
             * 标准事项申报提交方法
             */
//            String s = pjp.getSignature().getName();
            String query = request.getQueryString();
            if (query != null) {
                if (query.startsWith("?")) {
                    url += query;
                } else {
                    url += "?" + query;
                }
            }
            url = url.replace("http://wjw.szgaj.cn", "https://wjw.szgaj.cn");
            if ("standardItemAllSubmit".equals(pjp.getSignature().getName())) {
                MDC.put("method", pjp.getSignature().getName() + request.getParameter("standardid"));
                methodName = pjp.getSignature().getName() + request.getParameter("standardid");
            } else if ("submitPreExecute".equals(pjp.getSignature().getName())) {
                MDC.put("method", pjp.getSignature().getName() + request.getSession().getAttribute("hkyslid"));
                methodName = pjp.getSignature().getName() + request.getSession().getAttribute("hkyslid");
            } else {
                MDC.put("method", pjp.getSignature().getName());
                methodName = pjp.getSignature().getName();
            }
            MDC.put("url", url);
            MDC.put("args", getClientIP(request));
            //MDC.put("succ", isSucc);//在后面判断后再设置
            //MDC.put("result", result);//在后面判断后再设置
            //增加对访问来源的记录,openid的记录
            String source = (String) request.getSession().getAttribute("source");
            //session里没有就从页面参数拿,并且放入session中
//            System.out.println("ApicallAspect session中的source ====" + source);
            if (!StringUtils.hasText(source)) {
                source = request.getParameter("source");
                if (!StringUtils.hasText(source)) {
                    source = "szgawx";
                }
                request.getSession().setAttribute("source", source);
            }

            //判断是二维码就将isSucc设置成false
            if (source.indexOf("ewm") == 0 || "crj".equals(source)) {
                result = "ewm";
                isSucc = false;
                MDC.put("method", "ewm");
            }
            MDC.put("succ", isSucc);
            MDC.put("result", result);
            String ywid = (String) request.getSession().getAttribute("ywid");
            String location0 = (String) request.getSession().getAttribute("location0");
            String location1 = (String) request.getSession().getAttribute("location1");
            String remarks = (String) request.getSession().getAttribute("remarks");
            if (!StringUtils.isEmpty(ywid)) {
                MDC.put("ywid", ywid);
                request.getSession().removeAttribute("ywid");
            }
            if (!StringUtils.isEmpty(location0)) {
                MDC.put("location0", location0);
                request.getSession().removeAttribute("location0");
            }
            if (!StringUtils.isEmpty(location1)) {
                MDC.put("location1", location1);
                request.getSession().removeAttribute("location1");
            }
            if (!StringUtils.isEmpty(remarks)) {
                MDC.put("remarks", remarks);
                request.getSession().removeAttribute("remarks");
            }
            String openId = (String) request.getSession().getAttribute("openId");
            if (!StringUtils.hasText(openId)) {
//            	String state = request.getRequestURL().toString();
//            	String u = request.getContextPath()+"/oauth/oauth?state="+state;
//                request.getRequestDispatcher(u).forward(request, response);;
                openId = "null";
            }
            if (!StringUtils.hasText(source)) {
                source = "szgawx";
            }
//            System.out.println("openid===="+openId + "   "+source);
            MDC.put("source", source);
            MDC.put("openid", openId);
            if ("zwj".equals(source)) {
                MDC.put("source", "szgawx");
            }
            if (!"test".equals(source)) {
//                System.out.println("---要记录的地址"+url);
                client.info(url);
            }
            request.getSession().removeAttribute("source");

            /**
             * 	江苏公安微警务Pv上报接口
             */
            /*Map<String, String> paraMap = new HashMap<String, String>();
            String viewurl = url.replaceAll("https://wjw.szgaj.cn", "");
            if (viewurl.indexOf("?") > -1) {
                viewurl = viewurl.substring(0, viewurl.indexOf("?"));
            }
            Map<String, String> urlMap = (Map<String, String>) CommonUtilCache.getItem(viewurl);
            if (null != urlMap && !"null".equals(openId) && null != urlMap.get("appid")) {
                paraMap.put("city_open_id", openId);
                paraMap.put("app_id", urlMap.get("appid").toString());
                paraMap.put("App_key", urlMap.get("appkey").toString());
                paraMap.put("type", "0");
                PvThread t = new PvThread(paraMap);
                t.run();
            }*/
            /**
             * 	江苏公安微警务业务申报数据上报接口
             */
            /*if (viewurl.contains("/api/zzyc/movecar")) {
                System.out.println("methodName==============》》》" + viewurl);
                System.out.println("methodName==============》》》" + methodName);
                Map<String, String> methodMap = (Map<String, String>) CommonUtilCache.getItem(methodName);
                if (null != methodMap && !"null".equals(openId) && null != methodMap.get("appid")) {
                    paraMap.put("city_open_id", openId);
                    paraMap.put("app_id", methodMap.get("appid").toString());
                    paraMap.put("app_key", methodMap.get("appkey").toString());
                    paraMap.put("business_id", UUID.randomUUID().toString());
                    paraMap.put("business_date_time", DateUtil.getCurrentDateTime());
                    paraMap.put("status", "done");
                    paraMap.put("temp1", remarks);
                    paraMap.put("location0", location0);
                    paraMap.put("location1", location1);
                    BusinessThread t = new BusinessThread(paraMap);
                    t.run();
                }
            }

            Map<String, String> methodMap = (Map<String, String>) CommonUtilCache.getItem(methodName);
            if (null != methodMap && !"null".equals(openId) && null != methodMap.get("appid")) {
                paraMap.put("city_open_id", openId);
                paraMap.put("app_id", methodMap.get("appid").toString());
                paraMap.put("App_key", methodMap.get("appkey").toString());
                paraMap.put("type", "1");
                PvThread t = new PvThread(paraMap);
                t.run();
            }*/

        }
        return object;
    }


    /***
     * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP,
     *
     * @param request
     * @return
     */
    private static String getClientIP(HttpServletRequest request) {
        String fromSource = "X-Real-IP";
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
            fromSource = "X-Forwarded-For";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            fromSource = "Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            fromSource = "WL-Proxy-Client-IP";
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            fromSource = "request.getRemoteAddr";
        }
        //client.info("App Client IP: "+ip+", fromSource: "+fromSource);
        return ip;
    }

}
